import React, { Component } from 'react';
import { Tree, Input, message } from 'antd';
import axios from 'axios';
import { connect } from 'react-redux';
import store from '../../../../redux/index';

const TreeNode = Tree.TreeNode;
const Search = Input.Search;

const getParentKey = (key, tree) => {
  let parentKey;
  var oKey = key.toString();
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => node.id == oKey)) {
        parentKey = oKey;
      }
    }
  }
  return parentKey;
};


class RelationTree extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: '',
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      dataSource: [],
      intData: [],
      MenuOff: '',
      checkedKeys: [],
    };
  }

  componentWillMount() {
    var ID = store.getState().getGroup.ID;
    store.dispatch({ type: 'GroupOff', GroupOff: false });
    this.getTreeMenus(ID);
    this.getTreeChecked(ID);
  }

  componentWillUpdate(nextProps, nextState) {
    // console.log(nextProps.getGroup.GroupOff);
    var ID = store.getState().getGroup.ID;

    if (this.state.id == nextProps.getGroup.ID) {
      return false;
    } else {
      this.state.id = nextProps.getGroup.ID;
      if (nextProps.getGroup.GroupOff) {
        // 更新checked默认值
        // console.log('更新checked默认值-------------'+ID)
        this.getTreeChecked(ID);
      }

    }

  }
  // 获取左侧树菜单
  getTreeMenus = (ID) => {
    const _this = this;
    const Token = sessionStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/admin/menu/tree',
      headers: {
        Authorization: Token
      }
    })
      .then(function (response) {
        _this.setState({
          dataSource: response.data
        });
      })
      .catch(function (error) {
        console.log(error);
        message.error('服务器开小差啦，请重试！');
      });

  }
    // 获取左侧树菜单checked选中状态
    getTreeChecked = (ID) => {
      const _this = this;
      const Token = sessionStorage.getItem('token');
      axios({
        method: 'get',
        url: '/api/admin/group/' + ID + '/authority/menu',
        headers: {
          Authorization: Token
        }
      })
        .then(function (response) {
          var oCheckedData = [];
          response.data.data.forEach((item, key) => {
            // console.log(item);
            oCheckedData.push(String(item.id));
          });
          _this.setState({
            checkedKeys: oCheckedData,
            expandedKeys: oCheckedData,
            searchValue: ''
          });
          store.dispatch({ type: 'ChangeCheckedKeys', checkedKeys: _this.state.checkedKeys });
        })
        .catch(function (error) {
          console.log(error);
          message.error('服务器开小差啦，请重试！');
        });
    }

    onCheck = (checkedKeys) => {
      // console.log('onCheck', checkedKeys);
      this.setState({ checkedKeys });
      store.dispatch({ type: 'ChangeCheckedKeys', checkedKeys: checkedKeys });
      store.dispatch({ type: 'ChangeCheckedOff', checkedOff: true });
    }

  onSelect = (selectedKeys, info) => {
    this.setState({ selectedKeys });
    if (info.selectedNodes[0] != undefined) {
      this.props.getTableData(info.selectedNodes[0].props.id, store.getState().getGroup.ID);
    }
    store.dispatch({ type: 'ChangeCheckedOff', checkedOff: false });
  }

  onExpand = (expandedKeys) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  }
  onChange = (e) => {
    const value = e.target.value;
    const expandedKeys = this.state.dataSource.map((item) => {
      // console.log(item.title.indexOf(value))
      if (item.title.indexOf(value) >= -1) {
        return getParentKey(item.id, this.state.dataSource);
      }
      return null;
    }).filter((item) => item);
    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true,
    });
  }

  render() {
    const { searchValue, expandedKeys, autoExpandParent } = this.state;
    const loop = data => data.map((item, key) => {
      const index = item.title.indexOf(searchValue);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + searchValue.length);

      const title = index > -1 ? (
        <span>
          {beforeStr}
          <span style={{ color: '#f50' }}>{searchValue}</span>
          {afterStr}
        </span>
      ) : <span>{item.title}</span>;
      if (item.children) {
        return (
          <TreeNode key={item.id} title={title} id={item.id} parentId={item.parentId}>
            {loop(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={title} id={item.id} parentId={item.parentId} />;
    });
    return (
      <div>
        <Search style={{ marginBottom: 8 }} placeholder="请输入关键词过滤" onChange={this.onChange} value={this.state.searchValue} />
        <Tree
          checkable
          checkStrictly
          onExpand={this.onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          onSelect={this.onSelect}
          onCheck={this.onCheck}
          checkedKeys={this.state.checkedKeys}
        >
          {loop(this.state.dataSource)}
        </Tree>

        {/* <Tree
                    checkable
                    onExpand={this.onExpand}
                    expandedKeys={this.state.expandedKeys}
                    autoExpandParent={this.state.autoExpandParent}
                    onCheck={this.onCheck}
                    checkedKeys={this.state.checkedKeys}
                    onSelect={this.onSelect}
                    selectedKeys={this.state.selectedKeys}
                >
                    {this.renderTreeNodes(treeData)}
                </Tree> */}
      </div>
    );
  }
}

export default connect((state) => {
  return { ...state };
})(RelationTree);
